package com.gu.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author Mr.Gu
 * @date 2020/9/10 10:22
 * @function : File工具类
 **/
public class FileUtils {

    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 将上传得到的MultipartFile转换为本地临时file文件类型
     * 使用完后需要将存在本地的file文件删除
     * @param file
     * @return
     */
    public static File multipartFileToFile(MultipartFile file) {
        File toFile = null;
        InputStream ins = null;
        OutputStream os = null;
        try {
            if (file == null || file.getSize() <= 0) {
                log.warn("读取文件为空");
            } else {
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                os = new FileOutputStream(toFile);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return toFile;
    }

    /**
     * 删除存在本地的临时File文件
     * @param file
     */
    public static boolean deleteFile(File file) {
        boolean flag = false;
        if (file != null) {
            log.warn("读取file为空");
        }else {
            File file1 = new File(file.toURI());
            file1.delete();
            flag = true;
        }
        return flag;
    }

}
